import { PostService } from '~/server/database/services/postService'
import { requireAuth } from '~/server/utils/auth'

export default defineEventHandler(async (event) => {
  try {
    // 验证用户身份
    const user = await requireAuth(event)

    const id = parseInt(getRouterParam(event, 'id') || '0')
    
    if (!id || id <= 0) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Bad Request',
        data: { message: '无效的帖子ID' }
      })
    }

    // 检查帖子是否存在且用户有权限删除
    const existingPost = await PostService.getPostById(id)
    if (!existingPost) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Not Found',
        data: { message: '帖子不存在' }
      })
    }

    if (existingPost.authorId !== user.id && user.authority < 2) {
      throw createError({
        statusCode: 403,
        statusMessage: 'Forbidden',
        data: { message: '无权限删除此帖子' }
      })
    }

    const success = await PostService.deletePost(id)

    if (!success) {
      throw createError({
        statusCode: 500,
        statusMessage: 'Internal Server Error',
        data: { message: '删除帖子失败' }
      })
    }

    return {
      success: true,
      message: '帖子删除成功'
    }
  } catch (error: unknown) {
    console.error('删除帖子失败:', error)
    if (error && typeof error === 'object' && 'statusCode' in error) {
      throw error
    }
    throw createError({
      statusCode: 500,
      statusMessage: 'Internal Server Error',
      data: { message: '删除帖子失败' }
    })
  }
})
